package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.AccountRegisterController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.AccountRegisterModel;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.AccountRegisterParser.AccountRegisterParserInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 手机注册密码页
 * 
 * @author liyizhe
 * 
 */
public class MobileRegisterPwdActivity extends ActivityBase implements OnClickListener,
        IEventListener {

    private boolean isPasswordShowing = false;
    private ImageView mImgVisible = null;// 可见图标
    private EditText mEditPwd;// 密码
    private TextView mTextPoin;// 提示语
    private TextView mTextOk = null;// 确定

    private ToastDialog mLoadingDialog;// 底部loading

    private String mIdentifycodeString;
    private String mCurrentMobile;// 记录当前用户电话,一开始获取
    private String mCurrentPwd;// 记录当前用户密码，点击注册获取

    private final int INIT = EventTypeConstants.BASE;
    private final int SAVEDETAILS = INIT + 1;
    private final int INITSUCCESS = SAVEDETAILS + 1;
    private final int NETERROR = INITSUCCESS + 1;

    List<BasicNameValuePair> params;// 传的参数
    AccountRegisterParserInfo info = null;// 返回的信息

    AccountRegisterController controller;
    private CommonTitle mTitle;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case NETERROR:
                    hideLoadingDialog();
                    showMsg("网络连接超时");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (AccountRegisterController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_MAIL_MOBILE_REGISTER, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_phone_register_password);

        StatisticsUtils.onEvent(MobileRegisterPwdActivity.this,
                StatisticsEventID.ACCOUNT_MOBLE_RIGISTER_PWD);
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                // 读取数据 写处理逻辑
                info = (AccountRegisterParserInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            case EventTypeConstants.EVENT_EXC_IO_2:
                handler.sendEmptyMessage(NETERROR);
                break;
            default:
                handler.sendEmptyMessage(NETERROR);
                break;
        }
    }

    @Override
    public void activityLogicForward() {

        Intent intent = getIntent();
        mIdentifycodeString = intent.getStringExtra("identifycode");
        mCurrentMobile = intent.getStringExtra("phoneNumber");

        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mImgVisible = (ImageView) findViewById(R.id.img_psw_visible);
        mEditPwd = (EditText) findViewById(R.id.edit_password);
        mTextOk = (TextView) findViewById(R.id.complete_ok);
        mTextPoin = (TextView) findViewById(R.id.text_point);

        mImgVisible.setOnClickListener(this);
        mTextOk.setOnClickListener(this);
        
        mImgVisible.setImageResource(R.drawable.password_invisible);
        mEditPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        isPasswordShowing = false;
    }

    @Override
    public void activityInitData() {
        if (info != null) {
            String msg = info.message;
            if (info.resultCode.equals("200")) {
                updateUserInfoToDB(info);
                //showLoadingDialog(false, true, "注册成功");
                // 跳转到account页面 TODO
                 hideLoadingDialog();
                 AutoLogin();
                 LoginActivity.finishLoginAfterRegistOk(MobileRegisterPwdActivity.this);
            } else {
                showLoadingDialog(false, false, "注册失败！请重试");
            }
            if (!TextUtils.isEmpty(msg)) {
                showMsg(msg);
            }
        }
    }
    
    private void AutoLogin(){
        UserInfo user = new UserInfo();
        user.setUserId(info.uid);
        user.setNickName(info.nickName);
        user.setGender(info.gender);
        user.setSession(info.session);
        MyAccountManager.onLoginSuccess(this,user);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                this.finish();
                break;
            case R.id.img_psw_visible: {
                changePasswordShowState();
                break;
            }
            case R.id.complete_ok:
                StatisticsUtils.onEvent(MobileRegisterPwdActivity.this,
                        StatisticsEventID.ACCOUNT_MOBLE_RIGISTER_OVER);
                startRegister();
                break;
            default:
                break;
        }
    }
    
    
    private void changePasswordShowState(){
        if (isPasswordShowing) {
            isPasswordShowing = false;
            mImgVisible.setImageResource(R.drawable.password_invisible);
            mEditPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            if (!TextUtils.isEmpty(mEditPwd.getText().toString())) {
                mEditPwd.setSelection(mEditPwd.getText().toString()
                        .length());
            }
        } else {
            isPasswordShowing = true;
            mImgVisible.setImageResource(R.drawable.password_visible);
            mEditPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            if (!TextUtils.isEmpty(mEditPwd.getText().toString())) {
                mEditPwd.setSelection(mEditPwd.getText().toString()
                        .length());
            }
        }
    }

    /**
     * @Des 描述 获取接口组织参数
     * @return List<BasicNameValuePair>
     */
    public List<BasicNameValuePair> setParams() {
        List<BasicNameValuePair> pwParams = new ArrayList<BasicNameValuePair>();
        String strPwd = mEditPwd.getText().toString();

        String key = "c56cf32e9a52a265ae47cd50570266cc";
        long timestamp = System.currentTimeMillis();
        String strTimestamp = timestamp + "";
        String md5_key_sb = key + timestamp;
        String md5_key = Util.MD5(md5_key_sb.toString());
        pwParams.add(new BasicNameValuePair("key", md5_key));// md5
        pwParams.add(new BasicNameValuePair("timestamp", strTimestamp));// 时间戳

        pwParams.add(new BasicNameValuePair("type", AccountRegisterModel.TYPE_REGISTER_PHOEN));
        pwParams.add(new BasicNameValuePair("vcode", mIdentifycodeString));
        Log4an.d("liyizhe", "================" + mIdentifycodeString);
        pwParams.add(new BasicNameValuePair("account", mCurrentMobile));

        if (!TextUtils.isEmpty(strPwd)) {
            pwParams.add(new BasicNameValuePair("password", strPwd));
        }

        return pwParams;
    }


    /**
     * 点击注册
     */
    private void startRegister() {
        String strPwd = mEditPwd.getText().toString();
        mCurrentPwd = strPwd;

        boolean isOK = isEnableFormat();// 判断格式
        if (!isOK) {
            return;
        }

        showLoadingDialog(true, true, "正在注册");
        params = setParams();
        Log4an.d("liyizhe", "=========" + params);
        controller.handle(0, params);
    }

    /**
     * 判断输入的密码格式
     */
    private boolean isEnableFormat() {
        if (TextUtils.isEmpty(mCurrentPwd)) {
            mTextPoin.setText("请设置登录密码");
            mTextPoin.setTextColor(android.graphics.Color.parseColor("#ff361b"));
            return false;
        } else if (mCurrentPwd.length() > 16) {
            mTextPoin.setText("密码过长，请输入6-16位新密码");
            mTextPoin.setTextColor(android.graphics.Color.parseColor("#ff361b"));
            return false;
        } else if (mCurrentPwd.length() < 6) {
            mTextPoin.setText("密码过短，请输入6-16位新密码");
            mTextPoin.setTextColor(android.graphics.Color.parseColor("#ff361b"));
            return false;
        } else {
            mTextPoin.setText("可输入6-16位字符");
            mTextPoin.setTextColor(android.graphics.Color.parseColor("#494949"));
        }

        return true;
    }

    /**
     * 获得返回数据后保存
     * 
     * @param info
     */
    private void updateUserInfoToDB(AccountRegisterParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(mCurrentMobile)) {
            user.setMobile(mCurrentMobile);
        }
        if (!TextUtils.isEmpty(mCurrentPwd)) {
            user.setPassword(mCurrentPwd);
        }
        if (!TextUtils.isEmpty(info.uid)) {
            user.setUserId(info.uid);
        }
        if (!TextUtils.isEmpty(info.nickName)) {
            user.setNickName(info.nickName);
        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        if (!TextUtils.isEmpty(info.gender)) {
            user.setGender(info.gender);
        }
        AccountDao.getInstance().saveUserInfo(user);
//        UserInfoHelper.insertOrUpdateUserInfo(getApplicationContext(), user);
    }

    /**
     * 显示底部加载
     */
    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
